# from django.http import HttpResponse
from django.http import Http404
from django.db.models import Q
from django.shortcuts import render

from .models import Word, models
from WordBook.models import WordBook


# Create your views here.


def word_index(request, word_id):
    try:
        word = Word.objects.get(pk=word_id)
        # db 的get_word函数；
    except Word.DoesNotExist:
        raise Http404("Word does not exist.")

    # 寻找单词的公共单词本
    try:
        wordbook = word.wordbook.all()
    except wordbook.DoesNotExist:
        wordbook = ('无')
    wordbook = [i for i in wordbook]

    context = {
        'h_word': word,
        'h_wordbook': wordbook,
        'previous_id': word.word_id - 1,
        'next_id': word.word_id + 1,

    }

    return render(request, 'wordindex.html', context)


def word_display(request, word_id):
    try:
        word = Word.objects.get(pk=word_id)
    except Word.DoesNotExist:
        raise Http404("Word does not exist.")

    # 参数h_word表示html里面的word；
    # think：如何解析的，寻找字符串'h_word'，放入实参word（局部变量）
    return render(request, 'wordDisplay.html', {'h_word': word})


# 相当于是单词目录的总览，然后word_book界面肯定是会取代它的。
def word_default(request):
    # try:
    #     words=Word.objects.all()
    # except Word.DoesNotExist:
    #     raise Http404("Word does not exist.")
    words = Word.objects.all()

    return render(request, 'wordDefault.html', {'word_list': words})


# 定义search函数实现搜索单词功能
def search(request):
    q = request.GET.get('q')  # 获取用户提交关键词，数据通过表单保存在
    # request.GET中，类似字典，通过get（）方法取出对应值
    error_msg = ''
    word_list = Word.objects.filter(word_value__icontains=q)
    # icontains是查询表达式，__双下划线表示后面是待筛选属性，前缀i表示不区分大小写
    # Q对象为查询提供复杂逻辑判断
    if (not q) or not word_list:
        error_msg = '无匹配单词'
        return render(request, 'wordsearch.html', {'error_msg': error_msg})

    word_list = list(enumerate(word_list, 1))
    return render(request, 'wordsearch.html',
                  {'error_msg': error_msg, 'word_list': word_list,
                   'length': range(1, len(word_list) + 1)})
